<template>
  <div class="ascii-tool">
    <div class="tool-header">
      <h1>ASCII与Native编码转换工具</h1>
      <p>快速进行ASCII码与字符之间的转换</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 输入区域 -->
        <el-col :span="12">
          <div class="input-section">
            <div class="section-header">
              <h3>输入内容</h3>
              <div class="actions">
                <el-button @click="clearInput" size="small">清空</el-button>
                <el-button @click="pasteFromClipboard" size="small" type="primary">粘贴</el-button>
              </div>
            </div>
            
            <el-input
              v-model="inputText"
              type="textarea"
              :rows="8"
              placeholder="请输入要转换的文本或ASCII码..."
              @input="handleInput"
            />
            
            <div class="input-actions">
              <el-button 
                type="primary" 
                @click="textToAscii"
                :disabled="!inputText.trim()"
                :loading="isProcessing"
              >
                <el-icon><Lock /></el-icon>
                文本转ASCII
              </el-button>
              <el-button 
                type="success" 
                @click="asciiToText"
                :disabled="!inputText.trim()"
                :loading="isProcessing"
              >
                <el-icon><Unlock /></el-icon>
                ASCII转文本
              </el-button>
            </div>
          </div>
        </el-col>

        <!-- 输出区域 -->
        <el-col :span="12">
          <div class="output-section">
            <div class="section-header">
              <h3>转换结果</h3>
              <div class="actions">
                <el-button @click="copyResult" size="small" :disabled="!outputText">复制</el-button>
                <el-button @click="clearOutput" size="small">清空</el-button>
              </div>
            </div>
            
            <el-input
              v-model="outputText"
              type="textarea"
              :rows="8"
              placeholder="转换结果将显示在这里..."
              readonly
            />
            
            <div class="output-info" v-if="outputText">
              <el-tag type="info" size="small">
                长度: {{ outputText.length }} 字符
              </el-tag>
              <el-tag type="success" size="small" v-if="lastOperation">
                操作: {{ lastOperation }}
              </el-tag>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- ASCII对照表 -->
      <div class="ascii-table">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>ASCII对照表</span>
            </div>
          </template>
          
          <div class="ascii-content">
            <div class="ascii-section">
              <h4>控制字符 (0-31)</h4>
              <div class="ascii-grid">
                <div class="ascii-item" v-for="i in 32" :key="i">
                  <span class="ascii-code">{{ i - 1 }}</span>
                  <span class="ascii-char">{{ getAsciiChar(i - 1) }}</span>
                  <span class="ascii-desc">{{ getAsciiDescription(i - 1) }}</span>
                </div>
              </div>
            </div>
            
            <div class="ascii-section">
              <h4>可打印字符 (32-126)</h4>
              <div class="ascii-grid">
                <div class="ascii-item" v-for="i in 95" :key="i + 31">
                  <span class="ascii-code">{{ i + 31 }}</span>
                  <span class="ascii-char">{{ getAsciiChar(i + 31) }}</span>
                  <span class="ascii-desc">{{ getAsciiDescription(i + 31) }}</span>
                </div>
              </div>
            </div>
            
            <div class="ascii-section">
              <h4>扩展字符 (127-255)</h4>
              <div class="ascii-grid">
                <div class="ascii-item" v-for="i in 129" :key="i + 126">
                  <span class="ascii-code">{{ i + 126 }}</span>
                  <span class="ascii-char">{{ getAsciiChar(i + 126) }}</span>
                  <span class="ascii-desc">{{ getAsciiDescription(i + 126) }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 使用说明 -->
      <div class="tool-info">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>使用说明</span>
            </div>
          </template>
          
          <div class="info-content">
            <h4>什么是ASCII？</h4>
            <p>ASCII（American Standard Code for Information Interchange）美国信息交换标准代码，是基于拉丁字母的一套电脑编码系统，主要用于显示现代英语和其他西欧语言。</p>
            
            <h4>ASCII码范围：</h4>
            <ul>
              <li><strong>0-31：</strong>控制字符（不可打印）</li>
              <li><strong>32-126：</strong>可打印字符（空格、标点、数字、字母）</li>
              <li><strong>127：</strong>删除字符（DEL）</li>
              <li><strong>128-255：</strong>扩展ASCII字符</li>
            </ul>
            
            <h4>使用场景：</h4>
            <ul>
              <li>字符编码转换</li>
              <li>数据传输校验</li>
              <li>密码学应用</li>
              <li>文本处理</li>
              <li>编程调试</li>
            </ul>
            
            <h4>示例：</h4>
            <div class="example">
              <p><strong>文本：</strong>Hello</p>
              <p><strong>ASCII码：</strong>72 101 108 108 111</p>
              <p><strong>十六进制：</strong>48 65 6C 6C 6F</p>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Lock, Unlock } from '@element-plus/icons-vue'

const inputText = ref('')
const outputText = ref('')
const isProcessing = ref(false)
const lastOperation = ref('')

const handleInput = () => {
  // 输入变化时的处理逻辑
}

const textToAscii = async () => {
  if (!inputText.value.trim()) {
    ElMessage.warning('请输入要转换的文本')
    return
  }
  
  isProcessing.value = true
  try {
    // 模拟处理延迟
    await new Promise(resolve => setTimeout(resolve, 300))
    
    const asciiCodes = []
    for (let i = 0; i < inputText.value.length; i++) {
      const char = inputText.value[i]
      const ascii = char.charCodeAt(0)
      asciiCodes.push(ascii.toString())
    }
    
    outputText.value = asciiCodes.join(' ')
    lastOperation.value = '文本转ASCII'
    ElMessage.success('文本转ASCII完成')
  } catch (error) {
    ElMessage.error('转换失败：' + error.message)
  } finally {
    isProcessing.value = false
  }
}

const asciiToText = async () => {
  if (!inputText.value.trim()) {
    ElMessage.warning('请输入要转换的ASCII码')
    return
  }
  
  isProcessing.value = true
  try {
    // 模拟处理延迟
    await new Promise(resolve => setTimeout(resolve, 300))
    
    // 处理输入，支持空格、逗号、换行等分隔符
    const asciiCodes = inputText.value
      .split(/[\s,;\n\r]+/)
      .filter(code => code.trim())
      .map(code => parseInt(code.trim()))
      .filter(code => !isNaN(code) && code >= 0 && code <= 255)
    
    if (asciiCodes.length === 0) {
      throw new Error('没有找到有效的ASCII码')
    }
    
    const text = asciiCodes.map(code => String.fromCharCode(code)).join('')
    outputText.value = text
    lastOperation.value = 'ASCII转文本'
    ElMessage.success('ASCII转文本完成')
  } catch (error) {
    ElMessage.error('转换失败：' + error.message)
  } finally {
    isProcessing.value = false
  }
}

const getAsciiChar = (code) => {
  if (code < 32 || code === 127) {
    return '●' // 控制字符用圆点表示
  }
  if (code > 255) {
    return '?'
  }
  return String.fromCharCode(code)
}

const getAsciiDescription = (code) => {
  const descriptions = {
    0: 'NUL', 1: 'SOH', 2: 'STX', 3: 'ETX', 4: 'EOT', 5: 'ENQ', 6: 'ACK', 7: 'BEL',
    8: 'BS', 9: 'TAB', 10: 'LF', 11: 'VT', 12: 'FF', 13: 'CR', 14: 'SO', 15: 'SI',
    16: 'DLE', 17: 'DC1', 18: 'DC2', 19: 'DC3', 20: 'DC4', 21: 'NAK', 22: 'SYN', 23: 'ETB',
    24: 'CAN', 25: 'EM', 26: 'SUB', 27: 'ESC', 28: 'FS', 29: 'GS', 30: 'RS', 31: 'US',
    32: '空格', 127: 'DEL'
  }
  
  if (descriptions[code]) {
    return descriptions[code]
  }
  
  if (code >= 33 && code <= 126) {
    return '可打印字符'
  }
  
  if (code >= 128 && code <= 255) {
    return '扩展字符'
  }
  
  return ''
}

const clearInput = () => {
  inputText.value = ''
  ElMessage.info('已清空输入内容')
}

const clearOutput = () => {
  outputText.value = ''
  lastOperation.value = ''
  ElMessage.info('已清空输出结果')
}

const copyResult = async () => {
  if (!outputText.value) {
    ElMessage.warning('没有可复制的内容')
    return
  }
  
  try {
    await navigator.clipboard.writeText(outputText.value)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = outputText.value
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('已复制到剪贴板')
  }
}

const pasteFromClipboard = async () => {
  try {
    const text = await navigator.clipboard.readText()
    inputText.value = text
    ElMessage.success('已粘贴内容')
  } catch (error) {
    ElMessage.error('无法访问剪贴板，请手动粘贴')
  }
}
</script>

<style scoped>
.ascii-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.input-section,
.output-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.actions {
  display: flex;
  gap: 8px;
}

.input-actions {
  margin-top: 20px;
  display: flex;
  gap: 12px;
}

.output-info {
  margin-top: 15px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.ascii-table {
  margin: 40px 0;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.ascii-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.ascii-section h4 {
  color: #333;
  margin: 0 0 15px 0;
  font-size: 1.1rem;
  border-bottom: 2px solid #667eea;
  padding-bottom: 5px;
}

.ascii-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 8px;
  max-height: 300px;
  overflow-y: auto;
}

.ascii-item {
  display: grid;
  grid-template-columns: 40px 30px 1fr;
  gap: 8px;
  padding: 6px 8px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
  align-items: center;
  font-size: 0.85rem;
}

.ascii-code {
  font-weight: bold;
  color: #667eea;
  text-align: center;
}

.ascii-char {
  font-family: 'Courier New', monospace;
  color: #333;
  text-align: center;
  font-weight: bold;
}

.ascii-desc {
  color: #666;
  font-size: 0.8rem;
}

.tool-info {
  margin-top: 40px;
}

.info-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.info-content p {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
}

.info-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.info-content li {
  margin-bottom: 5px;
}

.example {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.example p {
  margin: 5px 0;
  font-family: 'Courier New', monospace;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .input-actions {
    flex-direction: column;
  }
  
  .output-info {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .ascii-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
  
  .ascii-item {
    grid-template-columns: 30px 20px 1fr;
    font-size: 0.8rem;
  }
}
</style>
